/**
 * 非原子操作执行序列
 */
#include <atomic>
#include <thread>
#include <assert.h>
#include <iostream>

bool x = false;
std::atomic<bool> y;
std::atomic<int> z;

void write_x_then_y() {
    x = true; // 非原子变量存储
    std::atomic_thread_fence(std::memory_order_release);
    y.store(true, std::memory_order_relaxed);
}

void read_y_then_x() {
    // 等待 y 存储完毕
    while (!y.load(std::memory_order_relaxed));
    std::atomic_thread_fence(std::memory_order_acquire);
    if (x) {
        ++z;
    }
}

int main(int argc, char const *argv[])
{
    x = false;
    y = false;
    z = 0;

    std::thread a(write_x_then_y);
    std::thread b(read_y_then_x);

    a.join();
    b.join();

    std::cout << "z is " << z << std::endl;
    
    return 0;
}
